package com.liang;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch ：闭锁，在完成某些运算是，只有其他所有线程的运算全部完成，当前运算才继续执行
 * @author: Liangxp
 * @date: 2019/7/31 20:25
 */
public class TestCountDownLatch4 {
    public static void main(String[] args) {
        final CountDownLatch countDownLatch = new CountDownLatch(50);
        LatchDemo latchDemo = new LatchDemo(countDownLatch);
        long start = System.currentTimeMillis();
        // 多线程执行任务
        for (int i = 0; i < 50; i++) {
            new Thread(latchDemo).start();
        }

        try {
            // 等待50个线程都执行完
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 所有线程执行完后计算时间
        long end = System.currentTimeMillis();
        System.out.println("耗费时间为：" + (end - start));
    }
}

class LatchDemo implements Runnable {
    private CountDownLatch countDownLatch;

    public LatchDemo(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
       try {
           for (int i = 0; i < 50000; i++) {
               if (i % 2 == 0) {
                   System.out.println(i);
               }
           }
       } finally {
           countDownLatch.countDown();
       }
    }
}
